package com.example.lib_common.custom

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.example.lib_common.R
import kotlin.math.min

/**
 * 自定义view 5秒倒计时
 */
class CircleCountDownView @JvmOverloads constructor(context: Context,attrs:AttributeSet ?= null,defStyleAttr:Int = 0):View(context,attrs)  {
    //属性变量
    private var progressBackgroundColor = Color.LTGRAY //背景圆环颜色
    private var progressColor = Color.BLUE //进度条颜色
    private var progressWidth = 20f //进度条宽度
    private var textColor = Color.BLACK //文字颜色
    private var textSize = 40f //文字大小
    private var countdownTime = 5 //倒计时时间

    //状态变量
    private var currentProgress = 0f //当前进度
    private var remainingTime = countdownTime //剩余时间
    private var centerX = 0f //圆心X坐标
    private var centerY = 0f //圆心Y坐标
    private var radius = 0f //圆半径

    //动画
    private var animator : ValueAnimator ? = null

    //监听器
    private var listener : CountDownListener ? = null

    //画笔
    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = progressBackgroundColor
        strokeWidth = progressWidth
        strokeCap = Paint.Cap.ROUND
    }

    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = progressColor
        strokeWidth = progressWidth
        strokeCap = Paint.Cap.ROUND
    }

    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = textColor
        textSize = this@CircleCountDownView.textSize
        textAlign = Paint.Align.CENTER
        typeface = Typeface.DEFAULT_BOLD
    }

    init {
        // 读取自定义属性
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.CircleCountDownView)
            try {
                progressColor = typedArray.getColor(
                    R.styleable.CircleCountDownView_progressColor,
                    progressColor
                )
                progressBackgroundColor = typedArray.getColor(
                    R.styleable.CircleCountDownView_progressBackgroundColor,
                    progressBackgroundColor
                )
                progressWidth = typedArray.getDimension(
                    R.styleable.CircleCountDownView_progressWidth,
                    progressWidth
                )
                textColor = typedArray.getColor(
                    R.styleable.CircleCountDownView_textColor,
                    textColor
                )
                textSize = typedArray.getDimension(
                    R.styleable.CircleCountDownView_textSize,
                    textSize
                )
                countdownTime = typedArray.getInteger(
                    R.styleable.CircleCountDownView_countdownTime,
                    countdownTime
                )
            } finally {
                typedArray.recycle()
            }
        }

        // 更新画笔属性
        backgroundPaint.strokeWidth = progressWidth
        backgroundPaint.color = progressBackgroundColor
        progressPaint.strokeWidth = progressWidth
        progressPaint.color = progressColor
        textPaint.textSize = textSize
        textPaint.color = textColor

        remainingTime = countdownTime
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        centerX = w/2f
        centerY = h/2f
        radius = (min(w,h) - progressWidth) /2f
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        //绘制背景圆环
        canvas.drawCircle(centerX,centerY,radius,backgroundPaint)

        //绘制进度弧线
        val sweepAngle = 360 * (currentProgress / 100f)
        canvas.drawArc(
            centerX - radius, centerY - radius,
            centerX + radius, centerY + radius,
            -90f, sweepAngle, false, progressPaint
        )

        // 3. 绘制文字
        val textY = centerY - (textPaint.descent() + textPaint.ascent()) / 2f
        canvas.drawText("${remainingTime}s", centerX, textY, textPaint)
    }
    /**
     * 开始倒计时
     */
    fun startCountDown() {
        stopCountDown() // 先停止之前的动画

        remainingTime = countdownTime
        currentProgress = 0f
        invalidate()

        animator = ValueAnimator.ofFloat(0f, 100f).apply {
            duration = (countdownTime * 1000).toLong()
            interpolator = LinearInterpolator()

            addUpdateListener { animation ->
                currentProgress = animation.animatedValue as Float

                // 计算剩余时间
                remainingTime = countdownTime - ((currentProgress / 100f) * countdownTime).toInt()

                // 确保在进度完成前一直显示至少1s
                if (remainingTime == 0 && currentProgress < 100f) {
                    remainingTime = 1
                }

                invalidate()

                // 倒计时结束
                if (currentProgress >= 100f) {
                    listener?.onCountDownFinished()
                }
            }
        }

        animator?.start()
    }

    /**
     * 停止倒计时
     */
    fun stopCountDown() {
        animator?.cancel()
        animator = null
    }

    /**
     * 设置倒计时监听器
     */
    fun setCountDownListener(listener: CountDownListener) {
        this.listener = listener
    }

    /**
     * 设置倒计时时间
     */
    fun setCountdownTime(seconds: Int) {
        this.countdownTime = seconds
        this.remainingTime = seconds
        invalidate()
    }

    /**
     * 设置进度条颜色
     */
    fun setProgressColor(color: Int) {
        progressPaint.color = color
        invalidate()
    }

    /**
     * 设置背景圆环颜色
     */
    fun setProgressBackgroundColor(color: Int) {
        backgroundPaint.color = color
        invalidate()
    }

    /**
     * 设置文字颜色
     */
    fun setTextColor(color: Int) {
        textPaint.color = color
        invalidate()
    }

    /**
     * 设置进度条宽度
     */
    fun setProgressWidth(width: Float) {
        progressWidth = width
        backgroundPaint.strokeWidth = width
        progressPaint.strokeWidth = width
        invalidate()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopCountDown()
    }





    //倒计时监听接口
    interface CountDownListener{
        fun onCountDownFinished()
    }
}